<template>
  <div class="coach-wrapper">
    <!-- 侧边栏 -->
    <transition name="sidebar">
      <div v-if="showSidebar" class="sidebar-overlay" @click="showSidebar = false">
        <div class="sidebar" @click.stop>
          <div class="sidebar-header">
            <h3>对话历史</h3>
            <button class="close-btn" @click="showSidebar = false">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
              </svg>
            </button>
          </div>
          
          <button class="new-chat-btn" @click="createNewChat">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <line x1="12" y1="5" x2="12" y2="19"></line>
              <line x1="5" y1="12" x2="19" y2="12"></line>
            </svg>
            新建对话
          </button>
          
          <div class="history-list">
            <div 
              v-for="session in historyList" 
              :key="session.session_id"
              :class="['history-item', { active: session.session_id === sessionId }]"
              @click="loadHistorySession(session.session_id)"
            >
              <div class="history-content">
                <div class="history-title">{{ session.first_message || '新对话' }}</div>
                <div class="history-time">{{ formatTime(session.created_at) }}</div>
              </div>
              <div class="message-count">{{ session.message_count || 0 }}</div>
            </div>
            
            <div v-if="historyList.length === 0" class="empty-history">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
              </svg>
              <p>暂无对话历史</p>
            </div>
          </div>
        </div>
      </div>
    </transition>
    
    <!-- 顶部导航栏 -->
    <div class="top-nav">
      <div class="nav-left">
        <svg class="menu-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" @click="toggleSidebar">
          <line x1="3" y1="6" x2="21" y2="6"></line>
          <line x1="3" y1="12" x2="21" y2="12"></line>
          <line x1="3" y1="18" x2="21" y2="18"></line>
        </svg>
      </div>
      <div class="nav-center">
        <div class="ai-logo">
          <div class="logo-gradient"></div>
        </div>
      </div>
      <div class="nav-right">
        <svg class="headphone-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M3 18v-6a9 9 0 0 1 18 0v6"></path>
          <path d="M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z"></path>
        </svg>
        <svg class="dropdown-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <polyline points="6 9 12 15 18 9"></polyline>
        </svg>
      </div>
    </div>

    <!-- 主要内容区域（可滚动） -->
    <div class="main-content">
      <!-- 欢迎语区域 - 只在没有消息时显示 -->
      <div class="welcome-section" v-if="messages.length === 0">
        <div class="quote-left">"</div>
        <h1 class="welcome-title">
          Hi，我是AI教练卡卡，<br/>请问有什么可以帮到你？
        </h1>
        <div class="quote-right">"</div>
      </div>

      <!-- 聊天消息区域 -->
      <div class="chat-messages" v-if="messages.length > 0">
        <div 
          v-for="(msg, index) in messages" 
          :key="index"
          :class="['message-item', msg.role === 'user' ? 'user-message' : 'assistant-message']"
        >
          <!-- 用户消息 -->
          <div v-if="msg.role === 'user'" class="message-bubble user-bubble">
            <div class="message-content">{{ msg.content }}</div>
          </div>
          
          <!-- AI 消息 -->
          <div v-else-if="msg.role === 'assistant'" class="message-bubble ai-bubble">
            <div class="ai-avatar">
              <div class="avatar-gradient"></div>
            </div>
            <div class="message-content">
              <div class="ai-name">AI教练卡卡</div>
              <div class="message-text" v-html="formatMarkdown(msg.content)" :key="`msg-${index}-${updateCounter}`"></div>
            </div>
          </div>
        </div>
        
        <!-- 加载中提示 - 只在还没有AI回复时显示 -->
        <div v-if="isLoading && messages.length > 0 && messages[messages.length - 1].role === 'user'" class="message-item assistant-message">
          <div class="message-bubble ai-bubble">
            <div class="ai-avatar">
              <div class="avatar-gradient"></div>
            </div>
            <div class="message-content">
              <div class="ai-name">AI教练卡卡</div>
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 功能卡片区域 - 只在没有消息时显示 -->
      <div class="features-grid" v-if="messages.length === 0">
        <div class="feature-card">
          <div class="icon-wrapper">
            <svg class="feature-icon calendar" viewBox="0 0 48 48" fill="none">
              <rect x="8" y="12" width="32" height="28" rx="2" stroke="currentColor" stroke-width="3"/>
              <path d="M8 20h32" stroke="currentColor" stroke-width="3"/>
              <path d="M16 8v8M32 8v8" stroke="currentColor" stroke-width="3" stroke-linecap="round"/>
            </svg>
          </div>
          <h3 class="feature-title">生成计划</h3>
          <p class="feature-desc">个性定制，打造最适合你的训练方案</p>
        </div>

        <div class="feature-card">
          <div class="icon-wrapper">
            <svg class="feature-icon food" viewBox="0 0 48 48" fill="none">
              <circle cx="24" cy="24" r="16" stroke="currentColor" stroke-width="3"/>
              <path d="M24 16v8l5.66 5.66" stroke="currentColor" stroke-width="3" stroke-linecap="round"/>
            </svg>
          </div>
          <h3 class="feature-title">记饮食</h3>
          <p class="feature-desc">拍照打卡，智能识别，轻松记录每一餐</p>
        </div>

        <div class="feature-card">
          <div class="icon-wrapper">
            <svg class="feature-icon evaluation" viewBox="0 0 48 48" fill="none">
              <path d="M12 36V28C12 26.8954 12.8954 26 14 26H18C19.1046 26 20 26.8954 20 28V36" stroke="currentColor" stroke-width="3"/>
              <path d="M24 16v20M24 16c0-2.2091 1.7909-4 4-4h4c2.2091 0 4 1.7909 4 4v20M24 16c0-2.2091-1.7909-4-4-4h-4c-2.2091 0-4 1.7909-4 4" stroke="currentColor" stroke-width="3" stroke-linecap="round"/>
            </svg>
          </div>
          <h3 class="feature-title">饮食评价</h3>
          <p class="feature-desc">突破瓶颈，全面分析你的饮食安排是否合理</p>
        </div>

        <div class="feature-card">
          <div class="icon-wrapper">
            <svg class="feature-icon weight" viewBox="0 0 48 48" fill="none">
              <rect x="12" y="16" width="24" height="20" rx="2" stroke="currentColor" stroke-width="3"/>
              <circle cx="24" cy="26" r="6" stroke="currentColor" stroke-width="3"/>
              <path d="M18 16v-4h12v4" stroke="currentColor" stroke-width="3"/>
            </svg>
          </div>
          <h3 class="feature-title">记体重</h3>
          <p class="feature-desc">上传拍个照，体重记录从未如此简单</p>
        </div>

        <div class="feature-card">
          <div class="icon-wrapper">
            <svg class="feature-icon exercise" viewBox="0 0 48 48" fill="none">
              <path d="M18 10L24 16L18 22M30 26L24 32L30 38" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M10 24h28" stroke="currentColor" stroke-width="3" stroke-linecap="round"/>
            </svg>
          </div>
          <h3 class="feature-title">记运动</h3>
          <p class="feature-desc">一键同步，上传运动数据图片即可记录</p>
        </div>

        <div class="feature-card">
          <div class="icon-wrapper">
            <svg class="feature-icon all-skills" viewBox="0 0 48 48" fill="none">
              <rect x="8" y="8" width="12" height="12" rx="2" stroke="currentColor" stroke-width="3"/>
              <rect x="28" y="8" width="12" height="12" rx="2" stroke="currentColor" stroke-width="3"/>
              <rect x="8" y="28" width="12" height="12" rx="2" stroke="currentColor" stroke-width="3"/>
              <rect x="28" y="28" width="12" height="12" rx="2" stroke="currentColor" stroke-width="3"/>
            </svg>
          </div>
          <h3 class="feature-title">全部技能</h3>
          <p class="feature-desc">点击查看全部教练技能</p>
        </div>
      </div>
    </div>

    <!-- 底部输入区域 -->
    <div class="bottom-input-bar">
      <!-- 快捷卡片 -->
      <div class="quick-cards">
        <button class="quick-card">
          <svg viewBox="0 0 24 24" fill="currentColor">
            <path d="M9 2h6v2H9V2zm3 18c-3.31 0-6-2.69-6-6h2c0 2.21 1.79 4 4 4s4-1.79 4-4h2c0 3.31-2.69 6-6 6zm-1-9H9v4h2v-4h2v4h2v-4h-2z"/>
          </svg>
          <span>生成计划</span>
        </button>
        <button class="quick-card">
          <svg viewBox="0 0 24 24" fill="currentColor">
            <path d="M8.1 13.34l2.83-2.83L3.91 3.5a4.008 4.008 0 0 0 0 5.66l4.19 4.18zm6.78-1.81c1.53.71 3.68.21 5.27-1.38 1.91-1.91 2.28-4.65.81-6.12-1.46-1.46-4.2-1.1-6.12.81-1.59 1.59-2.09 3.74-1.38 5.27L3.7 19.87l1.41 1.41L12 14.41l6.88 6.88 1.41-1.41L13.41 13l1.47-1.47z"/>
          </svg>
          <span>记饮食</span>
        </button>
        <button class="quick-card">
          <svg viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.31-8.86c-1.77-.45-2.34-.94-2.34-1.67 0-.84.79-1.43 2.1-1.43 1.38 0 1.9.66 1.94 1.64h1.71c-.05-1.34-.87-2.57-2.49-2.97V5H10.9v1.69c-1.51.32-2.72 1.3-2.72 2.81 0 1.79 1.49 2.69 3.66 3.21 1.95.46 2.34 1.15 2.34 1.87 0 .53-.39 1.39-2.1 1.39-1.6 0-2.23-.72-2.32-1.64H8.04c.1 1.7 1.36 2.66 2.86 2.97V19h2.34v-1.67c1.52-.29 2.72-1.16 2.73-2.77-.01-2.2-1.9-2.96-3.66-3.42z"/>
          </svg>
          <span>饮食评价</span>
        </button>
        <button class="quick-card">
          <svg viewBox="0 0 24 24" fill="currentColor">
            <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
          </svg>
          <span>记体重</span>
        </button>
      </div>
      <div class="input-wrapper">
        <input 
          type="text" 
          class="bottom-input" 
          placeholder="询问 AI 教练"
          v-model="inputText"
          @keyup.enter="sendMessage"
        />
        <button class="send-btn" @click="sendMessage" :disabled="!inputText.trim()">
          <svg viewBox="0 0 24 24" fill="currentColor">
            <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
          </svg>
        </button>
      </div>
      <div class="ai-notice">内容由 AI 生成</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const inputText = ref('')
const messages = ref([])
const isLoading = ref(false)
const sessionId = ref('')
const showSidebar = ref(false)
const historyList = ref([])
const updateCounter = ref(0) // 用于强制更新的计数器

// 生成唯一的 session_id（使用 UUID）
const generateSessionId = () => {
  return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
}

// 格式化 Markdown（简单处理换行）
const formatMarkdown = (text) => {
  if (!text) return ''
  return text
    .replace(/\n/g, '<br>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
}

// 加载历史记录
const loadHistory = async () => {
  try {
    const userId = userStore.user?.id || '2' // 如果没有用户信息，使用默认ID
    const token = userStore.token || localStorage.getItem('token') || ''
    
    const response = await fetch(
      `http://localhost:8000/api/history?user_id=${userId}&session_id=${sessionId.value}`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      }
    )
    
    if (!response.ok) {
      throw new Error('Failed to load history')
    }
    
    const data = await response.json()
    
    // 过滤掉 system 角色的消息，只显示 user 和 assistant 的对话
    messages.value = data.messages.filter(msg => msg.role !== 'system')
    
    console.log('历史记录加载成功:', messages.value.length, '条消息')
  } catch (error) {
    console.error('加载历史记录失败:', error)
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputText.value.trim() || isLoading.value) return
  
  const question = inputText.value.trim()
  const userId = userStore.user?.id || '2'
  
  // 添加用户消息到界面
  messages.value.push({
    role: 'user',
    content: question
  })
  
  // 清空输入框
  inputText.value = ''
  
  // 滚动到底部
  await nextTick()
  scrollToBottom()
  
  // 开始加载
  isLoading.value = true
  
  try {
    const token = userStore.token || localStorage.getItem('token') || ''
    
    const response = await fetch('http://localhost:8000/api/streamqa', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        question: question,
        user_id: userId,
        session_id: sessionId.value
      })
    })
    
    if (!response.ok) {
      throw new Error('Stream request failed')
    }
    
    // 创建 AI 回复消息
    const aiMessage = {
      role: 'assistant',
      content: ''
    }
    messages.value.push(aiMessage)
    
    // 读取流式响应
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let buffer = '' // 用于存储不完整的数据
    
    while (true) {
      const { done, value } = await reader.read()
      
      if (done) {
        console.log('流式传输完成')
        break
      }
      
      // 解码数据并添加到缓冲区
      buffer += decoder.decode(value, { stream: true })
      
      // 按行分割
      const lines = buffer.split('\n')
      
      // 保留最后一个可能不完整的行
      buffer = lines.pop() || ''
      
      for (const line of lines) {
        const trimmedLine = line.trim()
        
        // 跳过空行和注释
        if (!trimmedLine || trimmedLine.startsWith(':')) {
          continue
        }
        
        // 解析 SSE 数据
        if (trimmedLine.startsWith('data: ')) {
          try {
            const jsonStr = trimmedLine.slice(6) // 移除 'data: ' 前缀
            const data = JSON.parse(jsonStr)
            
            console.log('收到 SSE 数据:', data)
            
            if (data.type === 'message') {
              // 追加内容
              aiMessage.content += data.content
              
              // 强制触发响应式更新（更新计数器触发重新渲染）
              updateCounter.value++
              
              // 滚动到底部
              await nextTick()
              scrollToBottom()
            } else if (data.type === 'complete') {
              // 流式传输完成
              console.log('AI 回复完成')
            } else if (data.type === 'error') {
              // 错误处理
              console.error('AI 错误:', data.content)
              aiMessage.content = '抱歉，出现了一些问题，请稍后再试。'
            }
          } catch (e) {
            console.error('解析 SSE 数据失败:', e, '原始数据:', trimmedLine)
          }
        }
      }
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    
    // 添加错误提示
    messages.value.push({
      role: 'assistant',
      content: '抱歉，网络连接失败，请检查后端服务是否启动。'
    })
  } finally {
    isLoading.value = false
    
    // 滚动到底部
    await nextTick()
    scrollToBottom()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  const mainContent = document.querySelector('.main-content')
  if (mainContent) {
    mainContent.scrollTop = mainContent.scrollHeight
  }
}

// 切换侧边栏
const toggleSidebar = () => {
  showSidebar.value = !showSidebar.value
  if (showSidebar.value) {
    loadHistoryList()
  }
}

// 加载历史会话列表（从历史消息中提取会话列表）
const loadHistoryList = async () => {
  try {
    const userId = userStore.user?.id || '2'
    const token = userStore.token || localStorage.getItem('token') || ''
    
    // 调用历史记录接口，不传 session_id 获取所有历史消息
    const response = await fetch(
      `http://localhost:8000/api/history?user_id=${userId}`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      }
    )
    
    if (!response.ok) {
      throw new Error('Failed to load history')
    }
    
    const data = await response.json()
    console.log('历史记录接口返回数据:', data)
    
    // 直接使用返回的 sessions 数组
    if (data.sessions && Array.isArray(data.sessions)) {
      // 格式化数据以匹配界面显示需求
      historyList.value = data.sessions.map(session => ({
        session_id: session.session_id,
        first_message: session.last_message || '新对话',
        created_at: session.create_time || new Date().toISOString(),
        message_count: session.total || 0
      }))
      
      // 按创建时间排序（最新的在前）
      historyList.value.sort((a, b) => {
        const timeA = a.created_at ? new Date(a.created_at).getTime() : 0
        const timeB = b.created_at ? new Date(b.created_at).getTime() : 0
        return timeB - timeA
      })
    } else {
      historyList.value = []
    }
    
    console.log('历史会话列表:', historyList.value)
  } catch (error) {
    console.error('加载历史会话列表失败:', error)
    historyList.value = []
  }
}

// 加载指定的历史会话
const loadHistorySession = async (sessionIdToLoad) => {
  try {
    sessionId.value = sessionIdToLoad
    await loadHistory()
    showSidebar.value = false
    
    // 滚动到底部
    await nextTick()
    scrollToBottom()
  } catch (error) {
    console.error('加载历史会话失败:', error)
  }
}

// 创建新对话
const createNewChat = () => {
  sessionId.value = generateSessionId()
  messages.value = []
  inputText.value = ''
  showSidebar.value = false
  console.log('新建对话，会话ID:', sessionId.value)
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  
  const date = new Date(timestamp)
  const now = new Date()
  const diffMs = now - date
  const diffMins = Math.floor(diffMs / 60000)
  const diffHours = Math.floor(diffMs / 3600000)
  const diffDays = Math.floor(diffMs / 86400000)
  
  if (diffMins < 1) return '刚刚'
  if (diffMins < 60) return `${diffMins}分钟前`
  if (diffHours < 24) return `${diffHours}小时前`
  if (diffDays < 7) return `${diffDays}天前`
  
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${month}月${day}日`
}

// 页面加载时初始化
onMounted(() => {
  // 生成新的 session_id
  sessionId.value = generateSessionId()
  console.log('新会话 ID:', sessionId.value)
  
  // 不在页面加载时调用历史记录接口
  // 只有在用户点击侧边栏按钮时才加载历史记录
})
</script>

<style scoped>
.coach-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding-bottom: 56px; /* 为 TabBar 预留空间 */
  box-sizing: border-box;
  position: relative; /* 为侧边栏的 absolute 定位提供参照 */
}

/* 侧边栏遮罩 */
.sidebar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
}

/* 侧边栏 */
.sidebar {
  width: 80%;
  max-width: 320px;
  height: 100%;
  background: white;
  display: flex;
  flex-direction: column;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
}

/* 侧边栏头部 */
.sidebar-header {
  padding: 20px 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  padding: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background 0.2s;
}

.close-btn:hover {
  background: #f5f5f5;
}

.close-btn svg {
  width: 20px;
  height: 20px;
  color: #666;
}

/* 新建对话按钮 */
.new-chat-btn {
  margin: 16px;
  padding: 12px 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.new-chat-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.new-chat-btn:active {
  transform: translateY(0);
}

.new-chat-btn svg {
  width: 18px;
  height: 18px;
}

/* 历史记录列表 */
.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.history-item {
  padding: 12px;
  margin-bottom: 8px;
  background: #f8f9fa;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.history-item:hover {
  background: #e9ecef;
  transform: translateX(4px);
}

.history-item.active {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
  border: 1px solid rgba(102, 126, 234, 0.3);
}

.history-content {
  flex: 1;
  min-width: 0;
}

.history-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.history-time {
  font-size: 12px;
  color: #999;
}

.message-count {
  flex-shrink: 0;
  margin-left: 8px;
  padding: 4px 8px;
  background: #667eea;
  color: white;
  font-size: 12px;
  font-weight: 500;
  border-radius: 10px;
  min-width: 24px;
  text-align: center;
}

/* 空状态 */
.empty-history {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #999;
}

.empty-history svg {
  width: 64px;
  height: 64px;
  margin-bottom: 16px;
  opacity: 0.3;
}

.empty-history p {
  margin: 0;
  font-size: 14px;
}

/* 侧边栏动画 */
.sidebar-enter-active, .sidebar-leave-active {
  transition: opacity 0.3s;
}

.sidebar-enter-from, .sidebar-leave-to {
  opacity: 0;
}

.sidebar-enter-active .sidebar,
.sidebar-leave-active .sidebar {
  transition: transform 0.3s;
}

.sidebar-enter-from .sidebar,
.sidebar-leave-to .sidebar {
  transform: translateX(-100%);
}

/* 顶部导航栏 */
.top-nav {
  flex-shrink: 0;
  height: 60px;
  background: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  z-index: 100;
}

.nav-left, .nav-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.menu-icon, .headphone-icon, .dropdown-icon {
  width: 24px;
  height: 24px;
  color: #333;
  cursor: pointer;
}

.nav-center {
  flex: 1;
  display: flex;
  justify-content: center;
}

.ai-logo {
  width: 48px;
  height: 48px;
  position: relative;
}

.logo-gradient {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  border-radius: 50%;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.logo-gradient::before {
  content: '';
  position: absolute;
  top: 20%;
  left: 20%;
  width: 60%;
  height: 60%;
  background: white;
  border-radius: 50%;
  opacity: 0.2;
}

/* 主要内容区域（可滚动） */
.main-content {
  flex: 1;
  overflow-y: auto;
  background: linear-gradient(180deg, #e8eaf6 0%, #f5f5f7 100%);
  padding: 4px 16px 20px 16px;
}

/* 欢迎语区域 */
.welcome-section {
  text-align: center;
  margin-bottom: 8px;
  position: relative;
  padding: 20px 0;
}

.quote-left, .quote-right {
  position: absolute;
  font-size: 48px;
  font-weight: 300;
  color: #c5cae9;
  line-height: 1.5;
}

.quote-left {
  top: 0;
  left: 10px;
}

.quote-right {
  bottom: 0;
  right: 10px;
}

.welcome-title {
  font-size: 20px;
  font-weight: 600;
  color: #5c6bc0;
  line-height: 1.4;
  margin-top: 4px;
  margin-bottom: 0;
  padding: 0 20px;
}

/* 聊天消息区域 */
.chat-messages {
  margin-bottom: 16px;
}

.message-item {
  margin-bottom: 16px;
  display: flex;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.user-message {
  justify-content: flex-end;
}

.assistant-message {
  justify-content: flex-start;
}

.message-bubble {
  max-width: 80%;
  display: flex;
  gap: 10px;
}

.user-bubble {
  flex-direction: row-reverse;
}

.user-bubble .message-content {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 12px 16px;
  border-radius: 18px 18px 4px 18px;
  font-size: 15px;
  line-height: 1.5;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.ai-bubble {
  align-items: flex-start;
}

.ai-avatar {
  width: 36px;
  height: 36px;
  flex-shrink: 0;
}

.avatar-gradient {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  border-radius: 50%;
  position: relative;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.avatar-gradient::before {
  content: '';
  position: absolute;
  top: 20%;
  left: 20%;
  width: 60%;
  height: 60%;
  background: white;
  border-radius: 50%;
  opacity: 0.2;
}

.ai-bubble .message-content {
  flex: 1;
  background: white;
  padding: 12px 16px;
  border-radius: 18px 18px 18px 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.ai-name {
  font-size: 12px;
  color: #667eea;
  font-weight: 600;
  margin-bottom: 6px;
}

.message-text {
  font-size: 15px;
  line-height: 1.6;
  color: #333;
}

.message-text :deep(strong) {
  font-weight: 600;
  color: #667eea;
}

/* 打字指示器 */
.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 8px 0;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #667eea;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

/* 功能卡片区域 */
.features-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 12px;
}

.feature-card {
  background: white;
  border-radius: 12px;
  padding: 14px 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 120px;
  display: flex;
  flex-direction: column;
}

.feature-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
}

.icon-wrapper {
  margin-bottom: 8px;
}

.feature-icon {
  width: 32px;
  height: 32px;
}

.calendar {
  color: #7c4dff;
}

.food {
  color: #ff6b6b;
}

.evaluation {
  color: #a29bfe;
}

.weight {
  color: #6c5ce7;
}

.exercise {
  color: #00b894;
}

.all-skills {
  color: #5c6bc0;
}

.feature-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 6px 0;
}

.feature-desc {
  font-size: 12px;
  color: #999;
  line-height: 1.4;
  margin: 0;
  flex: 1;
}
/* 底部输入区域 */
.bottom-input-bar {
  flex-shrink: 0;
  background: #f5f5f5;
  padding: 12px 16px 8px 16px;
  z-index: 10;
  border-top: 1px solid #e5e5e5;
}

/* 快捷卡片 */
.quick-cards {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.quick-cards::-webkit-scrollbar {
  display: none;
}

.quick-card {
  flex-shrink: 0;
  background: white;
  border: none;
  border-radius: 8px;
  padding: 8px 12px;
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

.quick-card:active {
  transform: scale(0.96);
  background: #f8f8f8;
}

.quick-card svg {
  width: 18px;
  height: 18px;
  color: #555;
  flex-shrink: 0;
}

.quick-card span {
  font-size: 13px;
  color: #333;
  white-space: nowrap;
  font-weight: 500;
}

.input-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.bottom-input {
  flex: 1;
  height: 44px;
  border: none;
  border-radius: 22px;
  padding: 0 20px;
  font-size: 15px;
  background: white;
  outline: none;
  color: #333;
}

.bottom-input::placeholder {
  color: #bbb;
}

.send-btn {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  flex-shrink: 0;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.send-btn:active {
  transform: scale(0.95);
}

.send-btn:disabled {
  background: #e0e0e0;
  cursor: not-allowed;
  box-shadow: none;
}

.send-btn:disabled svg {
  color: #999;
}

.send-btn svg {
  width: 20px;
  height: 20px;
  color: white;
  transform: rotate(0deg);
}

.ai-notice {
  text-align: center;
  font-size: 10px;
  color: #999;
  line-height: 1.2;
}
</style>

